package com.blog.user.serviceImpl;


import com.blog.common.utils.Assert;
import com.blog.common.vo.JsonResult;
import com.blog.user.config.FileConfig;
import com.blog.user.mapper.FileMapper;
import com.blog.user.pojo.FileAttachment;
import com.blog.user.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName:DownLoadServiceImpl
 * @Author:wubo
 * @Data:2020/7/28 10:26
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Override
    public FileAttachment execute(String id) {
        Assert.valid(id,"请选择需要下载的文件");
        FileAttachment fileAttachment =fileMapper.downLoad(id);
        Assert.valid(fileAttachment,"下载文件可能已经不存在");
        return fileAttachment;
    }

    @Override
    public JsonResult upLoad(MultipartFile file) {
        try {
        String fileName = file.getOriginalFilename();
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String filePath = FileConfig.FILE_BASE_PATH+datePath;
        File dirFile = new File(filePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String realFileName=uuid+fileType;
        String realFilePath = filePath+realFileName;
        file.transferTo(new File(realFilePath));
        FileAttachment dataFile=new FileAttachment();
        dataFile.setNewId();
        dataFile.setPath(realFilePath);
        dataFile.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
        Date date = new Date();
        dataFile.setCreateTime(date);
        dataFile.setUpdateTime(date);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.fail("文件上传失败");
        }
        return JsonResult.success("上传成功!");
    }
}
